package com.graduation_design.modules.app.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation_design.common.lang.Result;
import com.graduation_design.entity.AppAddress;
import com.graduation_design.modules.app.annotation.Login;
import com.graduation_design.service.AppAddressService;
import com.graduation_design.service.AppProductService;
import com.graduation_design.service.AppUserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/app/address")
public class AddressController extends BaseController {

    @Resource
    AppAddressService appAddressService;

    @Resource
    AppUserService appUserService;

    @Login
    @GetMapping("info/{id}")
    public Result info(@PathVariable long id) {
        AppAddress appAddress = appAddressService.getById(id);
        Assert.isTrue(appAddress.getUserId().longValue() == appUserService.getCurrentUserId(), "收货地址不存在");
        return Result.success(appAddress);
    }

    @Login
    @GetMapping("/list")
    public Result list() {
        long userId = appUserService.getCurrentUserId();
        return Result.success(appAddressService.listByUserId(userId));
    }

    /**
     * 保存收货地址和修改默认
     */
    @Login
    @PostMapping("/save")
    public Result save(@Validated @RequestBody AppAddress appAddress) {
        appAddressService.saveAndDefault(appAddress);
        return Result.success();
    }

    @Login
    @PostMapping("/delete")
    public Result delete(Long id) {
        appAddressService.remove(new QueryWrapper<AppAddress>()
                .eq("id", id)
                .eq("user_id", appUserService.getCurrentUserId())
        );
        return Result.success();
    }
}
